<?php
/**
 * Created by PhpStorm.
 * User: jim
 * Date: 2016-12-22
 * Time: 21:05
 */
namespace App\Http\Controllers\home;
use App\Http\Controllers\Controller;
use App\Models\Count;
use App\Models\Store;
use App\Models\Product;
use Illuminate\Http\Request;
class DistanceController extends Controller
{
    /**
     *求两个已知经纬度之间的距离,单位为米
     * @param lng1 ,lng2 经度
     * @param lat1 ,lat2 纬度
     * @return float 距离，单位米
     **/
    function getdistance($lng1, $lat1, $lng2, $lat2)
    {
        //将角度转为狐度
        $lng1+=0;
        $lng2+=0;
        $lat1+=0;
        $lat2+=0;
        $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }
    /**
     *计算并选择距离定位坐标点最近的商户
     * @return location 位置信息
     **/
    function slstore(Request $request)
    {
        $city=$request->input('city');
        $district=$request->input('district');
        $street=$request->input('street');
        $lng2=$request->input('lng');
        $lat2=$request->input('lat');
        $list=Store::select('id','lng','lat','name')->get();
        $dist1=99999999;
        $store="";
        foreach ( $list as $v){
            $dist2=$this->getdistance($v->lng,$v->lat,$lng2,$lat2);
            if($dist1-$dist2>=0){
                $dist1=$dist2;
                $store=$v;
            }
        }
        //定位成功以后返回定位后的商家信息
        if($lng2){
            $store_id = $store->id;
            //$store_id = 1;
            //拉取定位后的商户的商品数据
            $list = Product::where('store_id', $store_id)
                ->paginate(6);
            //将定位后的位置信息存储至session
            $location=['city'=>$city,'district'=>$district,'street'=>$street,'store_id'=>$store_id,'dist'=>(round(($dist1/1000),2)),'name'=>$store->name];
            session(['location'=>$location]);
            //记录访问者访问商家id
            $timeip=date("Ymd",time()).$_SERVER['REMOTE_ADDR'];
            $res=Count::where('ip',$timeip)->first();
            $res->store_id=$store_id;
            $res->save();
            return $list->toJson();
        }else{
            $location= [
                'city'=>'定位失败！',
                'district'=>'',
                'street'=>'',
                'store_id'=>'',
                'name'=>'天安门大药房',
                'dist'=>" "
            ];
            session(['location'=>$location]);
            $list = Product::where('store_id', "1")
                ->paginate(6);
            return $list->toJson();
        }



    }
}